<script setup>
/**
 * @name 图文剪辑任务
 */
import {ref, reactive, onMounted, computed} from 'vue'
import request from "@/common/utils/request";
import {
  DeleteOutlined,
  EllipsisOutlined,
  ArrowDownOutlined,
  MoreOutlined
} from "@ant-design/icons-vue";
// 清理扩容组件
import kuarong from "@/views/shotstack/MaterialCenter/modules/kuarong.vue";
const kuarongRef = ref()

import CleaningModal from "@/views/shotstack/MaterialCenter/modules/CleaningModal.vue";

// 发布抽屉
import ImageTextIssue from './modules/ImageTextIssue.vue'
const ImageTextIssueRef = ref()

// 预览组内全部图片的抽屉
import viewGraphicImgDrawer from './modules/viewGraphicImgDrawer.vue'
const viewGraphicImgDrawerRef = ref()

import { graphic_columns } from './modules/index.js'

import { EyeOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue';

import { useRouter } from 'vue-router';
const router = useRouter();

const state = reactive({
  // 已使用空间
  capacityFormat: "",
  // 免费空间
  capacityToTalFormat: "",
  // 已使用空间百分比
  percent: 0,
  time: [],
    // 清理内存开关
  visibleCleaning: false,

  // table loading
  serchLoding: false,

  // 勾选的 keys
  selectedRowKeys:[],

  // 图文剪辑素材列表
  GraphicEditingTaskList: [],
  // 预览图片弹窗
  viewImgvisible: false,
  // 预览的图片链接
  imgUrl:''
})

const formState = reactive({
  page: 1,
  pageSize: 10,
  total:0
})

const resetSerch = () => {
  Object.assign(formState, {
    page: 1,
    pageSize: 10,
    total:0
  });
  state.time = []
  getList()
}

const serch = () => {
  formState.page = 1
  getList()
}

// 分页change事件
const PageChange = (page, pageSize) => {
  formState.page = page; //当前页码
  formState.pageSize = pageSize; //当前页数
  getList();
};

// 获取图文成片列表项
const getList = async () => {
  state.serchLoding = true
  const params = {
    ...formState,
    start_date: state.time?.[0],
    end_date: state.time?.[1],
  }
  try {
    const res = await request.get("/work_ai", "/user/image/clip/hight/group/list", params)
     console.log(res, '图文剪辑图集----列表数据');
   
     state.GraphicEditingTaskList = res.result.data
     formState.total = res.result.total
  } finally {
    state.serchLoding = false
  }
}

// 当前勾选的素材
const selectItems = computed(() => {
  return state.GraphicEditingTaskList.filter((item) =>item.checked);
});

// 获取剩余空间
const getCapacity = () => {
  request.get("/work_ai", "/user/shotstack/media/capacity").then((res) => {
    state.capacityFormat = res.capacityFormat;
    state.capacityToTalFormat = res.capacityToTalFormat;
    if (res.capacityToTalBytes >= 1) {
      state.percent = +(
        (Number(res.capacityBytes) / Number(res.capacityToTalBytes)) *
        100
      ).toFixed(1);
      return
    } 
    state.percent = 100
  });
};

// 打开预览弹窗
const showViewFilmRef = (id, item) => {
  viewGraphicImgDrawerRef.value?.open({id,item})
}

// 发布
const issue = (item) => {
  item.visible = false
  ImageTextIssueRef.value?.open({business_id:[item]})
}

//批量发布
const batchIssue = () => {
  if (selectItems.value.length == 0) {
    message.warning("请选择要发布的素材");
    return;
  }
  const ids = selectItems.value
  console.log(ids,'要上传的项目');
  
  ImageTextIssueRef.value?.open({business_id:ids})
}

// 删除单项
const deleteClick = async(item) => {
  item.visible = false
  const params = {
    detailIds:[item?.image_text_record_detail_id]
  }
  deleteData(params)
}

// 删除多项
const deleteItems = () => {
  console.log(selectItems,'当前勾选的项');
  const detailIds = selectItems.value.map(ele => ele.image_text_record_detail_id)
  const params = {
    detailIds
  }
  deleteData(params)
}

const deleteData = async(params) => {
  const res = await request.del("/work_ai", "/user/image/clip/high/group/delete", params)
  console.log(res, '删除的结果');
  message.success('删除成功!')
  formState.page = 1
  formState.pageSize  = 10
  getList()
}

// 扩容
const addMater = () => {
      kuarongRef.value?.showModal();
};

// 关闭内存弹窗
const onSubmitClean = () => {
    state.visibleCleaning = false;
  getCapacity();
};

// 去下载中心
const goDowloadCenter = () => {
  router.push({
    name: "Download",
  });
};

const downLoadLoading = ref(false)
const downLoad = async (params = {}) => {
  const {item = null} = params
  downLoadLoading.value = true
  const param = {
    ids: item ? [item.image_text_record_detail_id] : selectItems.value.map(ele => ele.image_text_record_detail_id)
  }
  try {
    const res = await request.put("/work_ai", "/user/image/clip/download", param)
    if(res?.code && res.code != 1000) throw new Error(res?.msg)
    console.log(res, '下载的情况??');
    message.success('下载任务提交成功,请在下载中心查看')
  } catch (error) {
    message.error(error.msg || '下载失败!')
  } finally {
    downLoadLoading.value = false
  }
}

onMounted(() => {
  getCapacity()
  getList()
})
</script>

<template>
    <div class="GraphicEditingTask">

            <!-- 顶部内容 -->
    <div class="title_box">
      <div class="memory">
        <a-row justify="space-between" align="middle">
          <a-col style="cursor: pointer; margin-right: 30px">
            <a-tooltip>
              <template #title
                >免费空间： {{ state.capacityToTalFormat }}
              </template>
              {{ state.capacityFormat }} / {{ state.capacityToTalFormat }}
              <span :style="percent >= 100 ? 'color: red' : 'color: #666'">
                (已使用: {{ (state.percent < 1 ? 1 : state.percent) + "%" }})
              </span>
            </a-tooltip>
          </a-col>
          <a-space>
            <a-col style="cursor: pointer" @click="state.visibleCleaning = true"
              ><delete-outlined style="margin-right: 5px" />清理</a-col
            >
            <a-col style="cursor: pointer" @click="addMater"
              ><inbox-outlined style="margin-right: 5px" />扩容</a-col
            >
            <a-col style="cursor: pointer" @click="goDowloadCenter"
              ><arrow-down-outlined class="qingli" />下载中心
            </a-col>
          </a-space>
        </a-row>
      </div>
    </div>

            <!-- 头部的搜索栏 -->
    <div class="serch_title">
      <div class="serch_left">

        <!-- @change="(e) => e.type == 'click' && getMediaList()" -->
        <!-- <div class="serch_item">
          <span class="left_prefix">剪辑名称</span>
          <a-input
            class="input_self"
            allow-clear
            style="width: 229px"
            v-model:value="state.keyword"
            placeholder="请输入关键字搜索"
          >
          </a-input>
        </div> -->

        <div class="serch_item">
          <span class="left_prefix">创建时间</span>
          <a-range-picker
            class="input_timer"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            style="width: 229px"
            v-model:value="state.time"
            show-time
          />
        </div>

        <a-button
          type="primary"
          :loading="state.serchLoding"
          @click="serch"
          >查询</a-button
        >
        <a-button :loading="state.serchLoding" @click="resetSerch"
          >重置</a-button
        >
      </div>
    </div>


    <div class="content_box">
        <!-- 素材列表 -->
        <div class="material_item_box">
          <template v-if="state.GraphicEditingTaskList.length">
          <div
            class="file-list"
            ref="containerRef"
            :gutter="{ xs: 8, sm: 16, md: 24 }"
            :wrap="true"
          >
            <div
              v-for="(item, index) in state.GraphicEditingTaskList"
              :key="item.id"
              style="width: 204px; cursor: pointer; margin-bottom: 15px"
              
            >
              <div class="file-item">
                <div style="width: 100%" class="content_box">
                  
                  <!-- 勾选 -->
                  <a-checkbox @click.top="()=>{}" class="item_checkbox" v-model:checked="item.checked"></a-checkbox>
                  <div class="type-box" @click="showViewFilmRef(item.id, item)">
                    <!-- 未完成总数 大于 成功的数量 (进行中) -->
                        <span class="schedule"
                          >图片数量 ({{
                            item?.medias?.length
                          }})</span
                        >
                    <img
                      v-lazy="item?.medias?.[0]?.material_url"
                      class="image"
                      style="height: 120px; object-fit: contain"
                      />
                      <!-- @load="imageLoaded(item)" -->
                  </div>
                  <div class="vidoe_msg_box">
                    <div class="title">
                      <a-tooltip>
                        <template #title>
                          {{ item.medias?.[0]?.material_name }}
                          <br>
                          创建时间:{{ item.created_at }}
                          <br>
                          修改时间:{{ item.updated_at }}
                          </template>
                        <span class="text_ellipsis">
                          {{ item.medias?.[0]?.material_name }}
                        </span>
                      </a-tooltip>

                      <!-- trigger="click" -->
                      <a-popover  placement="bottomLeft" v-model:visible="item.visible">
                        <template #content>
                          <div style="display: flex; flex-direction: column;">
                            <a-button
                              type="text"
                              style="width: 50px; text-align: center; padding: 0"
                              @click.stop="issue(item)"
                              >发布</a-button
                            >
                            <a-button
                              type="text"
                              style="width: 50px; text-align: center; padding: 0"
                              @click.stop="downLoad({item})"
                              >下载</a-button
                            >
                            <a-popconfirm title="确定要删除此项吗？" ok-text="确定" cancel-text="取消"
                            @confirm.stop="deleteClick(item)"
                            >
                                <a-button
                                  type="text"
                                  danger
                                  style="width: 50px; text-align: center; padding: 0"
                                  @click.stop=""
                                  >删除</a-button
                                >
                              </a-popconfirm>
    
                          </div>
                        </template>
                        <span @click.stop="() => {}" class="ellipsisOutlined">
                          <MoreOutlined />
                        </span>
                      </a-popover>
                    </div>

                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>

        <template v-else>
          <a-empty style="height: 200px; width: 100%; margin-top: 50px" />
        </template>
        </div>

              <!-- 分页器 -->
      <div style="display: flex; justify-content: flex-end;">
        <div class="page-total">共 {{ formState.total }} 条</div>
        <a-pagination
          :total="formState.total"
          :v-model:pageSize="formState.pageSize"
          v-model:current="formState.page"
          showSizeChanger="true"
          @change="PageChange"
        />
      </div>

    </div>

    <div class="control_btns" v-if="selectItems.length">
          <div class="all_choose">
            <!-- <a-checkbox
              :checked="isCheckedAll()"
              @change="checkedAllFn"
              style="margin-right: 10px"
            />
            全选 -->
            <div class="all_choose_text">
              已选择 {{ selectItems.length }} 个图集成片
            </div>
          </div>

          <a-button @click="batchIssue" :disabled="!selectItems.length" type="primary"
            >发布至平台
          </a-button>
          <a-button @click="downLoad" :loading="downLoadLoading" :disabled="!selectItems.length"
          >下载</a-button>
          <a-popconfirm title="确定要删除勾选项吗？" ok-text="确定" cancel-text="取消"
            @confirm.stop="deleteItems"
            >
            <a-button :disabled="!selectItems.length" danger
              >删除</a-button>
         </a-popconfirm>

        </div>

  </div>
  
  
  <kuarong
  :capacityToTalFormat="state.capacityToTalFormat"
  :ref="el => kuarongRef=el"
></kuarong>
    <!-- 清理内存 -->
    <CleaningModal
        :visible="state.visibleCleaning"
        @onCancel="state.visibleCleaning = false"
        @onSubmit="onSubmitClean"
    />

    <!-- 图片预览 -->
    <a-modal v-model:visible="state.viewImgvisible" title="图片预览" @ok="handleOk">
      <div class="view_img_content" :key="videoUrl">
        <img :src="state.imgUrl" alt="" />
      </div>

      <template #footer>
        <a-button @click="state.viewImgvisible = false">关闭</a-button>
      </template>

    </a-modal>

    <!-- 发布抽屉 -->
    <ImageTextIssue ref="ImageTextIssueRef" useType="图集成片"></ImageTextIssue>

    <!-- 查看组中的 图片 抽屉 -->
    <viewGraphicImgDrawer ref="viewGraphicImgDrawerRef"></viewGraphicImgDrawer>
</template>


<style lang="less" scoped>
.view_img_content {
width: 100%;
height: 500px;
display: flex;
justify-content: center;
background: #000000;

img {
height: 100%;
width: 100%;
object-fit: contain;
}
}
.GraphicEditingTask{
    padding: 0 20px;
    padding-left: 0;
    min-width: 950px;

    // 发布按钮
.control_btns {
    position: fixed;
    bottom: 0;
    display: flex;
    gap: 8px;
    transition: opacity 0.4s;
    background-color: #fff;
    align-items: center;
    padding: 20px;
    box-shadow: 0px 12px 16px rgba(0, 0, 0, 0.12),
      0px 6px 8px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
  }


      // 最头部标题和剩余空间
  .title_box {
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }


      // 第二层 搜索容器
  .serch_title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20px;
    margin-top: 10px;
    margin-bottom: 20px;

    .serch_left {
      display: flex;
      gap: 0 10px;

      .serch_item {
        display: flex;
        justify-content: center;
        align-items: center;

        .left_prefix {
          padding: 0 25px;
          background-color: #ffffff;
          line-height: 30px;
          border: 1px solid #d9d9d9;
          border-right: none;
        }
      }
    }
  }

    // 主要的项目列表和素材列表
    .content_box {

    // 下方素材列表
    .material_item_box {
      // display: flex;
      min-width: 920px;

      .file-list {
        // margin-top: 20px;
        display: grid;
        // justify-content: space-between;
        // gap: 20px;
        // flex-wrap: wrap;
        grid-template-columns: repeat(auto-fill, minmax(204px, 1fr));
        overflow: auto;
        min-width: 920px;

        .file-item {
          // background-color: #fff;
          border-radius: 7px;
          overflow: hidden;
          margin-right: 10px;
          // margin-bottom: 35px;
          // padding: 5px;
          display: flex;
          flex-direction: column;
          align-items: center;
          text-align: center;
          position: relative;
          cursor: pointer;

         .item_checkbox{
              position: absolute;
              left: 5px;
              top: 5px;
              z-index: 1;
            }

          .use_release {
            color: #0076ff;
            background: #d0d0d0;
            border-radius: 5px;
            padding: 2px 4px;
            font-weight: 500;
          }

          .badge {
            position: absolute;
            top: 28px;
            right: 25px;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 50%;
            color: #fff;
          }

          .icon-postion {
            position: absolute;
            top: 48px;
            left: 50px;
            font-size: 22px;
            cursor: pointer;
          }

          .image-box {
            margin-top: 40px;
            width: 100%;
            text-align: center;

            .image {
              width: 70px;
              height: 70px;
              border-radius: 4px;
              margin: 0 auto;
              position: relative;

              .image-mask {
                position: absolute;
                top: 0px;
                left: 0px;
                width: 70px;
                height: 70px;
                border-radius: 4px;
                background: rgba(0, 0, 0, 0.1);
                display: flex;
                align-items: center;
                justify-content: center;
                cursor: pointer;
                opacity: 0;
                color: #fff;

                .icon-eye-filled {
                  font-size: 24px;

                  &:hover {
                    color: #2878ff;
                  }
                }
              }

              &:hover {
                .image-mask {
                  opacity: 1;
                }
              }

              .durationText {
                position: absolute;
                left: 2px;
                bottom: 0px;
                color: #fff;
              }
            }

            .image-name {
              padding: 0 6px;
              height: 50px;
              padding-top: 5px;
              word-wrap: break-word;
            }

            .image-time {
              font-size: 12px;
              color: #9ea4aa;
            }
          }

          .content_box {
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            // 描述容器
            .vidoe_msg_box {
              // height: 60px;
              // padding: 12px 12px;
              // height: 100%;

              .title {
                text-align: left;
                font-weight: 700;
                margin-top: 5px;
                display: flex;
                justify-content: space-between;
                position: relative;

                .text_ellipsis {
                  display: inline-block;
                  // max-width: 200px; /* 设置最大宽度，根据需要调整 */
                  flex: 1;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  vertical-align: middle;
                  /* 根据需要调整 */
                }

                .ellipsisOutlined {
                  margin-left: 5px;
                }

                .ipt {
                  .confirm {
                    &:hover {
                      color: #2878ff;
                    }
                  }

                  .cancel {
                    &:hover {
                      color: #0076ff;
                    }
                  }
                }
              }

              // 底部描述

            }

            .type-box {
              width: 100%;
              height: 120px;
              position: relative;
              background-color: #000;
              border-radius: 8px;

              :deep(.ss-spin-nested-loading > div > .ss-spin .ss-spin-text) {
                text-shadow: none;
              }

              .schedule {
                position: absolute;
                right: 0;
                top: 0;
                z-index: 10;
                // background-color: #f3c548;
                background-color: #239842;
                color: #fff;
                font-size: 11px;
                padding: 2px 8px;
                border-radius: 0 0 0 8px;
              }

              .loding_item {
                // height: 100%;
                height: 120px;
                width: 100%;
                background-color: #dadada;
                align-items: center;
                padding: 15px;
                position: relative;
                overflow: hidden;
                cursor: pointer;
                border-radius: 5px;
                box-sizing: border-box;
                display: flex;
                flex-direction: column;
                justify-content: center;
                gap: 10px;

                .loding_progress {
                  width: 100%;
                }

                .loding_text {
                  font-weight: 600;
                }

                .loding_dec {
                  .loding_dec_text {
                    color: #9b9b9b;
                    margin-left: 5px;
                  }
                }
              }

              .text-box {
                width: 100%;
                height: 100%;

                color: #fff;
                background: rgba(0, 0, 0, 0.6);
                border-radius: 5px;
                padding: 20px;

                display: flex;
                justify-content: center;
                align-items: center;
                position: relative;

                .text {
                  display: -webkit-box;
                  -webkit-line-clamp: 4;
                  -webkit-box-orient: vertical;
                  overflow: hidden;
                  text-overflow: ellipsis;
                }
              }

              .image {
                width: 100%;
                height: 100%;
                object-fit: cover;
                border-radius: 8px;
              }

              .video-box {
                width: 100%;
                height: 120px;
                border-radius: 8px;
              }

              .duration {
                position: absolute;
                bottom: 5px;
                right: 8px;
                padding: 0 5px;
                border-radius: 5px;
                background: rgba(0, 0, 0, 0.3);
                color: #fff;
              }

              .status {
                position: absolute;
                bottom: 5px;
                left: 8px;
                padding: 0 5px;
                border-radius: 5px;
                // background: rgba(0, 0, 0, 0.3);
                color: #fff;
              }

              .status_active {
                &:hover {
                  color: var(--ss-primary-color);
                }
              }

              .audio-box {
                height: 100%;
                color: #fff;
                background: rgba(0, 0, 0, 0.6);
                border-radius: 8px;
                display: flex;
                justify-content: center;
                align-items: center;
              }
            }



          }
        }
      }
    }
  }

}
</style>